public class Solution_05 {
    public String longestPalindrome(String s) {
        int len = s.length();
        if (len<2) {
            return s;
        }
        //初始化最大回文长度
        int maxLen = 1;
        String res = s.substring(0,1);
        //中心位置枚举到len-2即可，即到了最后一个就不需要进行判断了
        for (int i=0;i<len-1;i++) {
            String oddStr = centerSpreed(s,i,i);
            String evenStr = centerSpreed(s,i,i+1);
            String maxStr = oddStr.length()>evenStr.length() ? oddStr : evenStr;
            if (maxStr.length() > maxLen) {
                maxLen = maxStr.length();
                res = maxStr;
            }
        }
        return res;
    }

    //返回回文字符串
    private String centerSpreed(String s,int left,int right) {
        int len = s.length();
        int i = left;
        int j = right;
        while (i>=0 && j<len) {
            if (s.charAt(i) == s.charAt(j)) {
                i--;
                j++;
            } else {
                break;
            }
        }
        //跳出来时s.charAt(i) != s.charAt(j),在此之前欧i--和j++操作
        return s.substring(i+1,j);
    }
}
